/**
 * 上传函数
 */
const qiniuUploader = require("qiniuUploader");

// 初始化七牛相关参数
function initQiniu() {
  var options = {
    uploadURL: 'https://up.qiniup.com',
    region: 'NCN', //
    uptokenURL: app.globalData.serviceUrl + "/wcComOrder/getToken",
    // uptoken: 'xxxx',
    domain: 'img.wc5818.com/',
  };
  qiniuUploader.init(options);
}

function upload(filePath, success, fail) {
  initQiniu();
  // 交给七牛上传
  qiniuUploader.upload(filePath, (res) => {
    success(res);
  }, (error) => {
    console.error('error: ' + JSON.stringify(error));
    fail(error);
  });
}


/**
 * 批量上传
 * @param images
 */
function batchUpload(images) {
  let uplist = []
  for (let index in images) {
    const path = images[index]['url'];
    const key = images[index]['key'];
    let promise = new Promise((resolve, reject) => {
      qiniuUploader.upload(path, (res) => {
        resolve(res.imageURL)
      }, (error) => {
        reject(error)
      }, {
          uploadURL: 'https://up.qiniup.com',
          region: 'ECN', //
          uptokenURL: app.globalData.serviceUrl + "/wcComOrder/getToken",
          key: key,
          domain: 'img.wc5818.com/',
        });
    })
    uplist.push(promise)
  }
  Promise.all(uplist).then((resultList) => {
    console.log(resultList);
    return resultList;
  }, error => {
    console.log(error)
    throw err;
  })
}

module.exports = {
  'upload': upload,
  'BatchUpload': batchUpload,
}